package com.ntt.benew.dictionary.api

import android.text.TextUtils
import com.blankj.utilcode.util.GsonUtils
import com.google.gson.reflect.TypeToken
import com.ntt.benew.dictionary.NttDictionaryManager
import com.ntt.benew.dictionary.entity.gpt.BaseEntity
import com.ntt.benew.dictionary.listener.OnTTSListener
import com.ntt.benew.dictionary.utils.ConcurrentCache
import com.ntt.benew.dictionary.utils.HttpUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Created by Android Studio.
 * User: tw
 * Date: 2023/11/6
 * Time: 19:14
 */
object BenewApiManager {

    val TTS_URL = "https://gw.benewtech.cn/tts/speech"

    private var cacheTTS = ConcurrentCache<String, String>(100)

    fun requestTTS(content: String, listener: OnTTSListener?) {
        val head = mutableMapOf(
            "Content-Type" to "application/json;charset=UTF-8",
            "Authorization" to "Bearer ${NttDictionaryManager.authToken}",
            "deviceId" to NttDictionaryManager.deviceId,
            "Accept" to "application/json",
            "Authorization" to "Bearer ${NttDictionaryManager.authToken}",
            "User-Agent" to HttpUtil.USER_AGENT + NttDictionaryManager.deviceVersion,
            "X-Device-User-Agent" to HttpUtil.USER_AGENT + NttDictionaryManager.deviceVersion,
        )
        val realText = content.trim()
        val tts = cacheTTS.get(realText)
        if (!TextUtils.isEmpty(tts)) {
            listener?.onSuccess(tts)
            return
        }

        CoroutineScope(Dispatchers.IO).launch {
            val result = HttpUtil.sendGetHttp("$TTS_URL?text=$realText", head)
            launch(Dispatchers.Main) {
                result?.let {
                    val data = GsonUtils.fromJson<BaseEntity<String>>(
                        it,
                        object : TypeToken<BaseEntity<String>>() {}.type
                    )
                    cacheTTS.put(realText, data.data ?: "")
                    listener?.onSuccess(data.data ?: "")
                }
            }
        }

    }

}